package com.hk.webapp.controller.admin;

import com.hk.webapp.bean.CmsArticle;
import com.hk.webapp.annotations.SkipPermission;
import com.hk.webapp.bean.CmsCategory;
import com.hk.webapp.service.CmsArticleService;
import com.hk.webapp.service.CmsCategoryService;
import com.hk.webapp.vo.CmsArticleQueryVo;
import com.hk.webapp.vo.EditArticleVo;
import com.hk.webapp.vo.IdsVo;
import com.hk.webapp.vo.ResultVo;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

@RestController
public class ArticleController extends AdminBaseController {

    @Resource
    private CmsArticleService cmsArticleService;
    @Resource
    private CmsCategoryService cmsCategoryService;

    @PostMapping("/Article/GetProps")
    public ResultVo getProps() {
        Field[] props = CmsArticle.class.getDeclaredFields();
        List<String> fieldList = new ArrayList<>();
        for (Field field : props) {
            fieldList.add(field.getName().replaceAll("[A-Z]", "_$0").toLowerCase());
        }
        return ResultVo.createBySuccessData(fieldList.parallelStream().filter(c -> !Arrays.asList("id", "create_time", "is_deleted", "category_id", "category_path", "state").contains(c)));
    }

    @SkipPermission
    @PostMapping("/Article/GetPageList")
    public ResultVo getPageList(@RequestHeader(value = "userId") Integer userId, @RequestBody CmsArticleQueryVo vo) {

        PageInfo<CmsArticle> list = cmsArticleService.searchPageList(vo,userId);
        //获取分类
        List<Integer> ids=list.getList().parallelStream().map(CmsArticle::getCategoryId).distinct().collect(Collectors.toList());
        if (ids.size()>0){
            List<CmsCategory> cateList= cmsCategoryService.getEntityListByIds(StringUtils.join(ids,","));
            for (CmsArticle item : list.getList()) {
                for (CmsCategory citem : cateList) {
                    if (item.getCategoryId()==citem.getId())
                    {
                        item.setFkBak1(citem.getName());
                    }
                }
            }
        }
        return ResultVo.createBySuccessData(list.getList(), list.getTotal());
    }

    @SkipPermission
    @PostMapping("/Article/GetDetail")
    public ResultVo getDetail(Integer id) {
        if (id <= 0) {
            return ResultVo.createByError("非法参数");
        }
        CmsArticle article = cmsArticleService.getEntityById(id);
        //获取分类
        CmsCategory cate = cmsCategoryService.getEntityById(article.getCategoryId());
        article.setFkBak1(cate.getName());
        return ResultVo.createBySuccessData(article);
    }

    @SkipPermission
    @PostMapping("/Article/CheckCode")
    public ResultVo checkCode(String code, Integer id) {
        if (StringUtils.isBlank(code)) {
            return ResultVo.createByError("参数不完整");
        }
        CmsArticle article = cmsArticleService.getEntityByCode(code, id);
        if (article != null) {
            return ResultVo.createByError("code已使用");
        } else {
            return ResultVo.createByError("code可用");
        }
    }

    @PostMapping("/Article/AddArticle")
    @ApiOperation("添加文章")
    public ResultVo addArticle(@RequestBody @Valid EditArticleVo vo) {
        if (StringUtils.isBlank(vo.getTitle()) || vo.getCategory_id() <= 0) {
            return ResultVo.createByError("非法参数");
        }
        //检查是否有关联
        CmsArticle article = new CmsArticle();
        if (vo.getRel_id()>0){
            CmsArticle rel_art = cmsArticleService.getEntityById(vo.getRel_id());
            if (rel_art==null)
            {
                return ResultVo.createByError("关联的数据不存在");
            }
            article = rel_art;
            article.setCategoryId(vo.getCategory_id());
            article.setRelId(vo.getRel_id());
            article.setWeight(vo.getWeight());
            article.setSort(vo.getSort());
        }else{
            article.setCategoryId(vo.getCategory_id());
            article.setContent(vo.getContent());
            article.setDescription(vo.getDescription());
            article.setImgsUrl(vo.getImgs_url());
            article.setImgUrl(vo.getImg_url());
            article.setLinkUrl(vo.getLink_url());
            article.setMetaTitle(vo.getMeta_title());
            article.setMetaKeywords(vo.getMeta_keywords());
            article.setMetaDescription(vo.getMeta_description());
            article.setSubTitle(vo.getSub_title());
            article.setTitle(vo.getTitle());
            article.setVideoUrl(vo.getVideo_url());
            article.setAttachment(vo.getAttachment());
            article.setAuthor(vo.getAuthor());
            article.setSource(vo.getSource());
            article.setPublishTime(vo.getPublish_time());
            article.setHitCount(vo.getHit_count());
            article.setSort(vo.getSort());
            article.setWeight(vo.getWeight());
            article.setIsTop(vo.getIs_top());
            article.setIsRecommend(vo.getIs_recommend());
            article.setState(vo.getState());
            article.setBakTitle(vo.getBak_title());
            article.setBakDescription(vo.getBak_description());
            article.setCode(vo.getCode());
            //article.setCreateTime(new Date());
            article.setCreateTime(vo.getPublish_time()==null?new Date():vo.getPublish_time());
            article.setRelId(vo.getRel_id());
        }
        if (cmsArticleService.insert(article) <= 0) {
            return ResultVo.createByError("添加失败");
        }
        return ResultVo.createBySuccessData("succeed");
    }

    @PostMapping("/Article/EditArticle")
    @ApiOperation("编辑文章")
    public ResultVo editArticle(@RequestBody @Valid EditArticleVo vo) {
        if (vo.getId() == 0 || vo.getCategory_id() == 0) {
            return ResultVo.createByError("非法参数");
        }
        CmsArticle article = cmsArticleService.getEntityById(vo.getId());
        if (article==null)
        {
            return ResultVo.createByError("数据不存在或已删除");
        }
        //判断是否有关联
        if (vo.getRel_id()>0){
            //获取对象
            CmsArticle rel_art = cmsArticleService.getEntityById(vo.getRel_id());
            if (rel_art==null)
            {
                return ResultVo.createByError("关联数据不存在");
            }
            //将关联的数据值更新到当前数据
            article = rel_art;
            article.setId(vo.getId());
            article.setCategoryId(vo.getCategory_id());
            //article.category_path = await _icms_category.GetCategoryPath(vm.category_id);
            article.setRelId(vo.getRel_id());
            article.setWeight(vo.getWeight());
            article.setSort(vo.getSort());
        }else{
            article.setId(vo.getId());
            article.setCategoryId(vo.getCategory_id());
            article.setContent(vo.getContent());
            article.setDescription(vo.getDescription());
            article.setImgsUrl(vo.getImgs_url());
            article.setImgUrl(vo.getImg_url());
            article.setLinkUrl(vo.getLink_url());
            article.setMetaTitle(vo.getMeta_title());
            article.setMetaKeywords(vo.getMeta_keywords());
            article.setMetaDescription(vo.getMeta_description());
            article.setSubTitle(vo.getSub_title());
            article.setTitle(vo.getTitle());
            article.setVideoUrl(vo.getVideo_url());
            article.setAttachment(vo.getAttachment());
            article.setAuthor(vo.getAuthor());
            article.setSource(vo.getSource());
            article.setPublishTime(vo.getPublish_time());
            article.setHitCount(vo.getHit_count());
            article.setSort(vo.getSort());
            article.setWeight(vo.getWeight());
            article.setIsTop(vo.getIs_top());
            article.setIsRecommend(vo.getIs_recommend());
            article.setState(vo.getState());
            article.setCreateTime(vo.getPublish_time()==null?article.getCreateTime():vo.getPublish_time());
            article.setBakTitle(vo.getBak_title());
            article.setBakDescription(vo.getBak_description());
            article.setCode(vo.getCode());
            article.setRelId(vo.getRel_id());
        }
        if (cmsArticleService.update(article) <= 0) {
            return ResultVo.createByError("编辑失败");
        }
        //关联更新
        List<CmsArticle> rel_artList = cmsArticleService.getEntityListByRelId(article.getId(),article.getId());
        if (rel_artList.size()>0)
        {
            for (CmsArticle item :rel_artList) {
                CmsArticle _art = article;
                _art.setId(item.getId());
                _art.setCategoryId(item.getCategoryId());
                //_art.category_path= await _icms_category.GetCategoryPath(item.category_id);
                _art.setRelId(item.getRelId());
                _art.setWeight(item.getWeight());
                _art.setSort(item.getSort());
                cmsArticleService.update(_art);
            }

        }
        return ResultVo.createBySuccessData("succeed");
    }

    @PostMapping("/Article/DelArticle")
    @ApiOperation("批量删除文章")
    public ResultVo delArticle(@RequestBody IdsVo vo) {
        if (vo.getIds().size() == 0) {
            return ResultVo.createByError("请选择要删除的项");
        }
        if (cmsArticleService.softDelByIds(vo.getIds()) > 0) {
            return ResultVo.createBySuccessData("succeed");
        }
        return ResultVo.createByError("删除失败");
    }
}
